﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Authentication;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;

namespace MyWebapi
{
    public class MyAuthorizeHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        public const string SchemeName = "MyAuthorizeHandler";
        private Sunxsh_01 _sunxsh;
        public MyAuthorizeHandler(Sunxsh_01 sunxsh, IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
            : base(options, logger, encoder, clock)
        {
            this._sunxsh = sunxsh;
        }
        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            if (Request.QueryString.HasValue) return Task.FromResult(AuthenticateResult.Fail(new AuthenticationException("未登录")));

            var claimsIdentity = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, _sunxsh.Name),
                new Claim(ClaimTypes.Role, _sunxsh.Age.ToString()),
			}, "RIS_Auth");

            var principal = new ClaimsPrincipal(claimsIdentity);
            return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName)));
        }
    }

    public class Sunxsh_01
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
